package sg.java.concepts.equals;

import org.apache.commons.lang.builder.HashCodeBuilder;

/**
 * This example illustrates the use of equals and the use of Apache Commons Lang
 * HashCodeBuilder for providing the implementation of hashcode.
 * 
 * @author Oh Chin Boon
 * 
 */
public class SimpleEqualsApp {
	public static void main(String args[]) {
		Truck truck;
		Truck truck1;
		Truck truck2;

		truck = new Truck();
		truck.setModel("Toyota");

		truck1 = new Truck();
		truck1.setModel("Toyota");

		truck2 = new Truck();
		truck2.setModel("Honda");

		System.out.println("Truck equals truck 1" + (truck == truck1));
		System.out.println("Truck equals truck 2" + (truck == truck2));
	}
}

class Truck {
	private String model;

	public String getModel() {
		return this.model;
	}

	public void setModel(final String model) {
		this.model = model;
	}

	/**
	 * Rule: Two truck objects are said to be equal if the model are the same.
	 * e.g. "Toyota == Toyota"
	 */
	public boolean equals(Object o) {
		boolean result;

		result = false;

		if ((o instanceof Truck)
				&& ((Truck) o).getModel().equalsIgnoreCase(this.model)) {
			result = true;
		}

		return result;
	}

	/**
	 * Using {@link Truck#model} to compute hashcode.
	 */
	public int hashCode() {
		return new HashCodeBuilder().append(this.model).toHashCode();
	}
}